package com.zx.flow.config;

import com.zx.flow.api.util.TraceUtil;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;

/**
 * @author zhangxue
 */
public class TraceServletFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            initTrace(request);
            chain.doFilter(request, response);
        } finally {
            TraceUtil.clearTrace();
        }
    }

    private void initTrace(ServletRequest request) {
        try {
            HttpServletRequest req = (HttpServletRequest) request;
            String traceId = req.getHeader(TraceUtil.TRACE_ID);
            if (StringUtils.isBlank(traceId)) {
                TraceUtil.initTrace();
            } else {
                TraceUtil.initTrace(traceId);
            }
        } catch (Exception e) {
            // 忽略
        }
    }
}
